package com.business.dashboard.controller;

import com.business.dashboard.entity.AdminUser;
import com.business.dashboard.model.AdminLoginRequest;
import com.business.dashboard.service.AdminUserService;
import com.business.dashboard.utils.JwtUtil;
import com.business.dashboard.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理员认证控制器
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/auth")
@Validated
public class AdminAuthController {

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public ResultUtil<Map<String, Object>> login(@RequestBody @Valid AdminLoginRequest request,
                                                 HttpServletRequest httpRequest) {
        try {
            log.info("管理员登录尝试，用户名: {}", request.getUsername());
            
            // 查找管理员用户
            AdminUser admin = adminUserService.getUserByUsername(request.getUsername());
            if (admin == null) {
                log.warn("用户不存在: {}", request.getUsername());
                return ResultUtil.error("用户名或密码错误");
            }
            
            log.info("找到用户: {}, 状态: {}, ID: {}", admin.getUsername(), admin.getStatus(), admin.getId());
            log.info("数据库密码: {}", admin.getPassword());
            log.info("输入密码: {}", request.getPassword());
            
            // 检查用户状态
            if (admin.getStatus() == 0) {
                log.warn("用户被禁用: {}", request.getUsername());
                return ResultUtil.error("账户已被禁用");
            }
            
            // 验证密码 - 兼容明文和BCrypt加密密码
            boolean passwordMatch = false;
            if (admin.getPassword() != null && admin.getPassword().startsWith("$2a$")) {
                // BCrypt加密密码
                passwordMatch = passwordEncoder.matches(request.getPassword(), admin.getPassword());
                log.info("使用BCrypt验证，匹配结果: {}", passwordMatch);
            } else {
                // 明文密码
                passwordMatch = request.getPassword().equals(admin.getPassword());
                log.info("使用明文验证，匹配结果: {}", passwordMatch);
            }
            
            if (!passwordMatch) {
                log.warn("密码错误，用户: {}", request.getUsername());
                return ResultUtil.error("用户名或密码错误");
            }
            
            // 生成JWT token
            String token = jwtUtil.generateAdminToken(admin.getId().toString());
            
            // 设置session（保持向后兼容）
            httpRequest.getSession().setAttribute("adminId", admin.getId());
            httpRequest.getSession().setAttribute("adminUsername", admin.getUsername());
            httpRequest.getSession().setAttribute("adminNickname", admin.getNickname());
            
            // 更新登录信息
            String clientIp = getClientIpAddress(httpRequest);
            adminUserService.updateLoginInfo(admin.getId(), clientIp);
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("admin", buildAdminResponse(admin));
            result.put("expiresIn", 86400); // 24小时
            result.put("message", "登录成功");
            
            return ResultUtil.success("登录成功", result);
        } catch (Exception e) {
            log.error("管理员登录失败", e);
            return ResultUtil.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 管理员退出登录
     */
    @PostMapping("/logout")
    public ResultUtil<String> logout(HttpServletRequest request) {
        try {
            // 清除session
            request.getSession().invalidate();
            return ResultUtil.success("退出登录成功");
        } catch (Exception e) {
            log.error("退出登录失败", e);
            return ResultUtil.error("退出登录失败");
        }
    }

    /**
     * 获取当前管理员信息
     */
    @GetMapping("/me")
    public ResultUtil<AdminUser> getCurrentAdmin(HttpServletRequest request) {
        try {
            // 从session获取管理员ID
            Object adminIdObj = request.getSession().getAttribute("adminId");
            if (adminIdObj == null) {
                return ResultUtil.error(401, "未登录");
            }
            
            Long adminId = (Long) adminIdObj;
            AdminUser admin = adminUserService.getUserById(adminId);
            if (admin != null) {
                // 清除敏感信息
                admin.setPassword(null);
                return ResultUtil.success("获取成功", admin);
            } else {
                return ResultUtil.error(404, "管理员不存在");
            }
        } catch (Exception e) {
            log.error("获取管理员信息失败", e);
            return ResultUtil.error("获取管理员信息失败：" + e.getMessage());
        }
    }


    /**
     * 更新当前管理员个人信息
     */
    @PutMapping("/profile")
    public ResultUtil<AdminUser> updateProfile(HttpServletRequest httpRequest,
                                             @RequestBody Map<String, String> request) {
        try {
            // 从session获取管理员ID
            Object adminIdObj = httpRequest.getSession().getAttribute("adminId");
            if (adminIdObj == null) {
                return ResultUtil.error(401, "未登录");
            }
            
            Long adminId = (Long) adminIdObj;
            AdminUser admin = adminUserService.getUserById(adminId);
            if (admin == null) {
                return ResultUtil.error("管理员不存在");
            }
            
            // 更新允许的字段
            String nickname = request.get("nickname");
            String email = request.get("email");
            String phone = request.get("phone");
            
            if (nickname != null && !nickname.trim().isEmpty()) {
                admin.setNickname(nickname.trim());
            }
            
            if (email != null && !email.trim().isEmpty()) {
                // 简单的邮箱格式验证
                if (!email.contains("@") || !email.contains(".")) {
                    return ResultUtil.error("邮箱格式不正确");
                }
                admin.setEmail(email.trim());
            }
            
            if (phone != null && !phone.trim().isEmpty()) {
                admin.setPhone(phone.trim());
            }
            
            // 更新管理员信息
            AdminUser updatedAdmin = adminUserService.updateUser(admin);
            
            // 清除敏感信息
            updatedAdmin.setPassword(null);
            
            return ResultUtil.success("个人信息更新成功", updatedAdmin);
        } catch (Exception e) {
            log.error("更新管理员个人信息失败", e);
            return ResultUtil.error("更新个人信息失败：" + e.getMessage());
        }
    }

    /**
     * 修改管理员密码
     */
    @PutMapping("/password")
    public ResultUtil<String> changePassword(HttpServletRequest httpRequest,
                                            @RequestBody Map<String, String> request) {
        try {
            String oldPassword = request.get("oldPassword");
            String newPassword = request.get("newPassword");
            
            if (oldPassword == null || oldPassword.trim().isEmpty()) {
                return ResultUtil.error("原密码不能为空");
            }
            
            if (newPassword == null || newPassword.trim().isEmpty()) {
                return ResultUtil.error("新密码不能为空");
            }
            
            if (newPassword.length() < 6) {
                return ResultUtil.error("新密码长度不能少于6位");
            }
            
            // 从session获取管理员ID
            Object adminIdObj = httpRequest.getSession().getAttribute("adminId");
            if (adminIdObj == null) {
                return ResultUtil.error(401, "未登录");
            }
            
            Long adminId = (Long) adminIdObj;
            AdminUser admin = adminUserService.getUserById(adminId);
            if (admin == null) {
                return ResultUtil.error("管理员不存在");
            }
            
            // 验证原密码 - 兼容明文和BCrypt加密密码
            boolean oldPasswordMatch = false;
            if (admin.getPassword() != null && admin.getPassword().startsWith("$2a$")) {
                // BCrypt加密密码
                oldPasswordMatch = passwordEncoder.matches(oldPassword, admin.getPassword());
            } else {
                // 明文密码
                oldPasswordMatch = oldPassword.equals(admin.getPassword());
            }
            
            if (!oldPasswordMatch) {
                return ResultUtil.error("原密码错误");
            }
            
            // 更新密码
            admin.setPassword(passwordEncoder.encode(newPassword));
            adminUserService.updateUser(admin);
            
            return ResultUtil.success("密码修改成功");
        } catch (Exception e) {
            log.error("修改管理员密码失败", e);
            return ResultUtil.error("修改密码失败：" + e.getMessage());
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }

    /**
     * 验证token（session）
     */
    @PostMapping("/validate")
    public ResultUtil<Map<String, Object>> validateToken(HttpServletRequest request) {
        try {
            // 从session获取管理员ID
            Object adminIdObj = request.getSession().getAttribute("adminId");
            if (adminIdObj == null) {
                return ResultUtil.error(401, "Token无效或已过期");
            }
            
            Long adminId = (Long) adminIdObj;
            AdminUser admin = adminUserService.getUserById(adminId);
            if (admin == null || admin.getStatus() == 0) {
                // 清除无效session
                request.getSession().invalidate();
                return ResultUtil.error(401, "用户不存在或已被禁用");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("valid", true);
            result.put("admin", buildAdminResponse(admin));
            
            return ResultUtil.success("Token验证成功", result);
        } catch (Exception e) {
            log.error("Token验证失败", e);
            return ResultUtil.error(401, "Token验证失败");
        }
    }

    /**
     * 构建管理员响应对象
     */
    private Map<String, Object> buildAdminResponse(AdminUser admin) {
        Map<String, Object> adminMap = new HashMap<>();
        adminMap.put("id", admin.getId());
        adminMap.put("username", admin.getUsername());
        adminMap.put("email", admin.getEmail());
        adminMap.put("name", admin.getNickname());
        adminMap.put("phone", admin.getPhone());
        adminMap.put("avatar", admin.getAvatar());
        adminMap.put("status", admin.getStatus());
        adminMap.put("lastLoginTime", admin.getLastLoginTime());
        return adminMap;
    }

}